//
//  NavigationBarController.swift
//  BWUIKit
//
//  Created by zhuxuhong on 2022/2/18.
//

import UIKit
import SnapKit
import BWListKit
 
class CustomNavigationBar: View {
    lazy var bar: NavigationBar = {
        let v = NavigationBar()
        v.isOpaque = true
        v.isTranslucent = false
        return v
    }()
    
    open override func didInit() {
        super.didInit()
        
        addSubview(bar)
        bar.snp.makeConstraints { make in
            make.leading.top.bottom.trailing.equalToSuperview()
            make.height.equalTo(44)
        }
    }
    
    override func safeAreaInsetsDidChange() {
        super.safeAreaInsetsDidChange()
        
        bar.snp.updateConstraints { make in
            make.top.equalTo(safeAreaInsets.top)
        }
    }
}

open class NavigationBarController: TableViewController {
    private lazy var customNavBar: CustomNavigationBar = {
        let v = CustomNavigationBar()
        v.backgroundColor = .white
        v.isHidden = true
        v.bar.items = [customNavItem]
        return v
    }()
    
    private lazy var customNavItem: UINavigationItem = {
        let v = UINavigationItem()
        v.title = title
        return v
    }()
    
    private var needsResetOriginalNavBarHidden = false
    
    private func setupCustomNavBar(){
        navBarTransparent = true
        
        view.addSubview(customNavBar)
        customNavBar.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
        }
    }
    
    open override func didLoad() {
        super.didLoad()
        
        setupCustomNavBar()
    }
    
    open override func willAppear() {
        super.willAppear()
        
        if let v = navigationController?.isNavigationBarHidden, v == false {
            navigationController?.setNavigationBarHidden(true, animated: true)
            needsResetOriginalNavBarHidden = true
        }
    }
    
    open override func didLayout() {
        super.didLayout()
        
        view.bringSubviewToFront(customNavBar)
        customNavBar.isHidden = false
    }
    
    open override func willDisapppear() {
        super.willDisapppear()
        
        if needsResetOriginalNavBarHidden {
            navigationController?.setNavigationBarHidden(false, animated: true)
        }
    }
    
    public override var navItem: UINavigationItem? {
        return customNavItem
    }
    public override var navBar: UINavigationBar? {
        return customNavBar.bar
    }
    
    open override var navBarBackgroundColor: UIColor? {
        get {
            return customNavBar.backgroundColor
        }
        set{
            customNavBar.backgroundColor = newValue
        }
    }
    open override var navBarBarTintColor: UIColor? {
        get {
            return customNavBar.backgroundColor
        }
        set{
            customNavBar.backgroundColor = newValue
        }
    }
}
